package com.babyqiao.wallpaper.manager.service.impl;

import com.babyqiao.wallpaper.manager.service.LocalStorageService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * @author qinglongzhai
 * @date 2020/12/9
 */
@Service
public class LocalStorageServiceImpl implements LocalStorageService {
    @Value("${local.image.uploaddic}")
    private String imageDic;


    @Override
    public String uploadFileCover(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //文件名
        String filename = file.getOriginalFilename();
        //获取UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //拼接出最终的文件名
        filename = uuid + filename;

        //获取当前日期
        String dataPath = new DateTime().toString("yyyy-MM-dd");
        //创建文件目录
        File fileDir = new File(imageDic + dataPath);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }

        //输出路径
        OutputStream outputStream = new FileOutputStream(fileDir + "/" + filename);

        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        inputStream.close();
        outputStream.close();
        /**
         * 返回文件路径 /image/为虚拟路径，对应于WallpaperWebMvcConfig类中的pathPatterens
         * */
        String url = "/image/" + dataPath + "/" + filename;
        return url;
    }
}
